package org.wotou.authority.system;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.wotou.authority.dto.UserCookieDTO;
import org.wotou.authority.utils.Constant;
import org.wotou.authority.utils.JwtUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局拦截器
 *
 * @Author zhangQ
 * @Date 2017/12/14 23:17
 */
public class MyInterceptor implements HandlerInterceptor {
    //本地异常日志记录对象
    private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class);

    /**
     * 动作交互之前拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        logger.info("开始拦截！");
        String sessionToken = this.getCookieVal(httpServletRequest.getCookies(), Constant.ACCESS_TOKEN);
        if (null != sessionToken && sessionToken.length() > 0) {
            /*
            * 1.如果有加密信息获取JWT加密信息，解密获得userCookieDTO对象
            * 2.获取过期时间，如果过期返回 401错误
            * */
            UserCookieDTO userCookie = (UserCookieDTO) JwtUtil.unsign(sessionToken, UserCookieDTO.class);
            System.out.println(userCookie);
            Boolean isCheckluj = true;

            // 没有通过
            if (!isCheckluj) {
                httpServletResponse.setStatus(401);
                return false;
            }
        }
        if (!(httpServletRequest.getRequestURI().equals("/authority/wtuser/checkLogin") || httpServletRequest.getRequestURI().equals("/authority/wtuser/addUser"))) {
            return false;
        }
        return true;
    }

    /**
     * 动作交互之后，生成试图之前拦截
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 渲染之后 处理内存释放
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("afterCompletion");
    }

    /**
     * 获得指定cookie的值
     *
     * @param cookies
     * @param cookieKey
     * @return
     */
    protected String getCookieVal(Cookie[] cookies, String cookieKey) {
        if (null == cookies || cookieKey.isEmpty()) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookieKey.equals(cookie.getName())) {
                return cookie.getValue();
            }
        }
        return null;
    }
}
